//package keer.httpinterface.http;
//
//import keer.httpinterface.HttpInterfaceException;
//import keer.httpinterface.utils.StringUtils;
//
//import javax.net.ssl.SSLSocketFactory;
//import java.io.*;
//import java.net.Socket;
//import java.net.URL;
//import java.util.concurrent.atomic.AtomicLong;
//
//public class SocketHttpRequester extends AbstractHttpRequester {
//    private final static String HTTP = "http";
//    private final static String HTTPS = "https";
//    private final static int DEFAULT_HTTP_PORT = 80;
//    private final static int DEFAULT_HTTPS_PORT = 443;
//    private final static String HTTP_VERSION = "HTTP/1.1";
//    private final static String NEW_LINE = "\r\n";
//    private final static String TRANSFER_ENCODING_CHUNK = "chunked";
//    private final static long EMPTY_LENGTH = -1;
//    private Socket socket;
//    private HttpProperties properties;
//
//    @Override
//    protected void configure0(HttpProperties properties) throws Exception {
//        this.properties = properties;
//    }
//
//    protected Socket createSocket(URL url) throws Exception {
//        String protocol = url.getProtocol();
//        Socket socket = null;
//        int port = url.getPort();
//        if (HTTP.equals(protocol)) {
//            if (port <= 0) {
//                port = DEFAULT_HTTP_PORT;
//            }
//            socket = new Socket(url.getHost(), port);
//        } else if(HTTPS.equals(protocol)) {
//            if (port <= 0) {
//                port = DEFAULT_HTTPS_PORT;
//            }
//            socket = SSLSocketFactory.getDefault().createSocket(url.getHost(), port);
//        } else {
//            throw new HttpInterfaceException("Unsupported protocol:" + protocol);
//        }
//        socket.setSoTimeout(properties.getReadTimeoutMillis().intValue());
//        socket.setKeepAlive(Boolean.TRUE);
//        socket.setTcpNoDelay(Boolean.TRUE);
////        socket.connect(new InetSocketAddress(url.getHost(), port));
////        socket.connect();
//        return socket;
//    }
////
////    private Socket createHttpSocket(String host, int port) throws IOException {
////        if (port <= 0) {
////            port = DEFAULT_HTTP_PORT;
////        }
////        return new Socket(host, port);
////    }
////
////    private Socket createHttpsSocket(String host, int port) throws IOException {
////        if (port <= 0) {
////            port = DEFAULT_HTTPS_PORT;
////        }
////        return SSLSocketFactory.getDefault().createSocket(host, port);
////    }
//
//    @Override
//    protected HttpResponse request0(HttpRequest request) throws Exception {
//        URL url = new URL(request.getUrl());
//        if (socket == null) {
//            socket = createSocket(url);
//        }
//        StringBuilder message = new StringBuilder();
//        String path = StringUtils.isBlank(url.getPath()) ? "/" : url.getPath();
//        path += StringUtils.isBlank(url.getQuery()) ? "" : " " + url.getQuery();
//        message.append(request.getMethod().name())
//                .append(" ").append(path)
//                .append(" ").append(HTTP_VERSION).append(NEW_LINE)
//                .append("Host: ").append(url.getHost()).append(NEW_LINE);
//        for (String key : request.getHeaders().all().keySet()) {
//            for (String v : request.getHeaders().get(key)) {
//                message.append(v).append(": ").append(v).append(NEW_LINE);
//            }
//        }
//        message.append(NEW_LINE);
//        HttpResponse.Builder builder = HttpResponse.builder();
//        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//        InputStreamWrapper input = new InputStreamWrapper(reader);
//        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//        writer.write(message.toString());
//        writer.flush();
//        Headers headers = readHeader(reader);
//        builder.headers(headers);
//        builder.content(createContent(headers, input));
//        return builder.build();
//    }
//
//    public static void main(String[] args) throws HttpInterfaceException {
//        String url = "http://baidu.com";
//        SocketHttpRequester requester = new SocketHttpRequester();
//        requester.configure(new HttpProperties());
//        requester.request(HttpRequest.Get(url));
//    }
//
//    private Headers readHeader(BufferedReader reader) throws IOException {
//        Headers headers = new Headers();
//        String line = null;
//        boolean ended = false;
//        while ((line = reader.readLine()) != null) {
//            if (ended) {
////                System.out.println("ended====================================" + line);
//                break;
//            }
//            if (StringUtils.isBlank(line)) {
//                ended = true;
//                continue;
//            }
//            headers.put(line);
//        }
//        return headers;
//    }
//
//    private InputStream createContentLenghtInputStream(InputStreamWrapper input, long contentLength) {
//        AtomicLong read = new AtomicLong(0);
//        long canRead = contentLength - input.read;
//        return new InputStream() {
//            @Override
//            public int read() throws IOException {
//                long current = read.getAndIncrement();
//                System.out.println(current);
//                if (current >= canRead) {
//                    return -1;
//                }
//                return input.read();
//            }
//        };
//    }
//
//    private InputStream createChunkInputStream(InputStream source) {
//        BufferedReader reader = new BufferedReader(new InputStreamReader(source));
//        return new InputStream() {
//            private byte[] buff = null;
//            private int index = 0;
//            @Override
//            public int read() throws IOException {
//                if (buff == null || index >= buff.length) {
//                    String line = reader.readLine();
//                    int size = Integer.parseInt(line, 16);
//                    if (size == 0) {
//                        return -1;
//                    }
//                    buff = new byte[size];
//                    int c = source.read(buff);
//                    if (c <= 0) {
//                        return -1;
//                    }
//                }
//                return buff[index++] & 0xFF;
//            }
//        };
//    }
//
//    private InputStream createContent(Headers headers, InputStreamWrapper source) {
//        long contentLength = headers.contentLength();
//        if (contentLength != EMPTY_LENGTH) {
//            return createContentLenghtInputStream(source, contentLength);
//        }
//        String transferEncoding = headers.transferEncoding();
//        if (TRANSFER_ENCODING_CHUNK.equals(transferEncoding)) {
//            return createChunkInputStream(source);
//        }
//        return source;
//    }
//
//    private static class InputStreamWrapper extends InputStream {
//        private final BufferedReader source;
//        private long read;
//
//        private InputStreamWrapper(BufferedReader source) {
//            this.source = source;
//            this.read = 0;
//        }
//
//        @Override
//        public int read() throws IOException {
//            this.read++;
////            System.out.println(read);
//            return source.read();
//        }
//
//    }
//}
